# -*- coding: utf-8 -*-

"""
ref:
    http://notebook.kulchenko.com/education/drawing-trees-with-turtles
"""

import random
import turtle as tl

f = 0.5     # how much shorter the next tree should be
a = 60      # what angle to use to turn the branches

def to_color(c):
    if len(c) < 3:
        return c
    else:
        cc = (int(c[0]), int(c[1]), int(c[2]))
        return cc

def draw_tree(d, n):
    '''
    绘制分形树函数

    d - distance to grow
    n - level for recursion
    '''

    if n == 0: return

    ps = n
    pc = (127, (8-n)*32, 0)

    tl.pensize(ps)
    tl.pencolor(pc)

    tl.forward(2/3*d)
    tl.right(a)
    draw_tree(d*f, n-1)
    tl.left(a)

    tl.pensize(ps)
    tl.pencolor(pc)

    tl.forward(1/3*d)
    tl.right(7)
    draw_tree(d*f, n-1)
    tl.left(7)

    tl.left(a)
    draw_tree(d*f, n-1)
    tl.right(a)

    tl.pensize(ps)
    tl.pencolor(pc)
    tl.backward(d)

def draw():
    '''
    绘制分形树
    '''

    tl.speed('fastest')
    tl.colormode(255)
    tl.tracer(8, 0)

    # point turtle up as trees grow up
    tl.left(90)

    # grow a large tree
    tl.penup()
    tl.goto(0, -120)
    tl.pendown()
    draw_tree(160, 6)

    # grow a small bush
    tl.penup()
    tl.goto(-80, -120)
    tl.pendown()
    draw_tree(80, 6)

    # grow grass
    for grass in range(-180, 180):
        tl.penup()
        tl.goto(grass+random.random()*5, -130+random.random()*25)
        tl.pendown()
        draw_tree(8, 3)

    tl.ht()


if __name__ == '__main__':
    draw()
    tl.mainloop()